package vn.ugame.module.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.StoreService;
import vn.ugame.model.entity.Item;
import vn.ugame.module.AbstractModule;
import vn.ugame.module.ActionConfig;
import vn.ugame.module.Module;
import vn.ugame.module.Param;

public class DownloadModule extends AbstractModule implements Module {

    @ActionConfig(urlPattern = {"^(?<itemId>\\w+)$"})
    public void download(@Param("itemId") String itemId)
            throws ServletException, IOException {
        //Check Authorized
        Object principal = getRequest().getSession().getAttribute("AuthPrincipal");
        if (principal == null) {
            getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //Get email from principal
        String email = principal.toString();

        //Get Item
        Item item = null;
        StoreService store = new StoreService();
        try {
            item = store.findLocalItem(itemId, new Locale("en-us"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (item == null) {
            getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        //Get item path
        String itemPath = null;
        String userAgent = getRequest().getHeader("User-Agent");        
        if(userAgent.contains("Android")){
            itemPath = "/items/files/"+item.getPath()+".apk";
        }else if(userAgent.contains("OS X")){
            itemPath = "/items/files/"+item.getPath()+".ipa";
        }else{
            getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        //Get real path of item
        String realPath = getContext().getRealPath(itemPath);
        //Get mine type of the 
//        String mimeType = getContext().getMimeType(realPath);
        //Process mine type of item not found
//        if (mimeType == null) {
//            getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//            return;
//        }
        //Set content type
//        getResponse().setContentType(mimeType);
        //Set content size
        File file = new File(realPath);
        getResponse().setContentLength((int) file.length());
        //Set header
        getResponse().setHeader( "Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" );
        //Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = getResponse().getOutputStream();
        //Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        //Close all streams
        in.close();
        out.close();
        
        //Add Download Log
        try {            
            store.createDownloadItemLog(itemId, email);
        } catch (Exception ex) {
           ex.printStackTrace();
        }
    }
}
